package com.intel.factorytest.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.os.SystemProperties;
import android.os.storage.StorageManager;
import android.os.storage.StorageEventListener;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.intel.factorytest.R;
import com.intel.factorytest.activity.SensorsTestActivity.ItemInfo;
import com.intel.factorytest.adapter.GridAdapter;
import com.intel.factorytest.application.MATApplication;
import com.intel.factorytest.cfparser.ConfigFileParseUtil;
import com.intel.factorytest.cfparser.concrete.AConfigFileParser;
import com.intel.factorytest.cfparser.concrete.PropertiesConfParser;
import com.intel.factorytest.log.LogWriter;
import com.intel.factorytest.util.SDCardUtil;
import com.intel.factorytest.util.Util;

/**
 * 综合测试目前包括：电池状态，内外部存储器，USB，OTG
 */
public class ComprehensiveTest extends BaseActivity {

    private static final String TEST_CASE_NAME = "ComprehensiveTest";
    private static final String TAG = "ComprehensiveTest";

    private boolean doBatteryStatusCheckTest = true;
    private boolean doSdCardReadTest = true;
    private boolean doUSBTest = true;
    private boolean doOTGTest = true;
    private boolean doRFCalibStatus = false;

    private boolean resultBatteryOK = false;
    private boolean resultSDCardOK = false;
    private boolean resultUsbOK = false;
    private boolean resultOtgOK = false;
    private boolean resultRFCalibOK = false;

    private boolean resultCharging = false;

    private List<SensorsTestActivity.ItemInfo> mInfoList = new ArrayList<SensorsTestActivity.ItemInfo>();
    private BaseAdapter mGridAdapter;
    private GridView mGridView;

    // Comprehensive test value format: ComprehensiveTest=1;Battery status
    // check=1;Internal/External memory=1;USB=1;OTG(Mouse,Udisk)=1
    private String confValue;

    // testcase name
    private static final String TC_BatteryStatusCheck = "Battery status check";
    private static final String TC_SdCard = "Internal/External memory";
    private static final String TC_USB = "USB";
    private static final String TC_OTG = "OTG(Mouse,Udisk)";
    private static final String TC_RFCalib = "RF";

    private static final String TC_BatteryStatusCheck_zh = "电池状态检测";
    private static final String TC_SdCard_zh = "存储器";
    private static final String TC_USB_zh = "USB";
    private static final String TC_OTG_zh = "OTG(鼠标,U盘)";
    private static final String TEST_CASE_NAME_zh = "综合测试";
    private static final String TC_RFCalib_zh = "射频校正";

    private static final Map<String, String> nameMapping_language = new HashMap<String, String>();
    static {
        nameMapping_language.put(TC_BatteryStatusCheck,
                TC_BatteryStatusCheck_zh);
        nameMapping_language.put(TC_SdCard, TC_SdCard_zh);
        nameMapping_language.put(TC_USB, TC_USB_zh);
        nameMapping_language.put(TC_OTG, TC_OTG_zh);
        nameMapping_language.put(TEST_CASE_NAME, TEST_CASE_NAME_zh);
    }

    // index
    private static final int INDEX_BatteryStatus = 0;
    private static final int INDEX_SdCard = 1;
    private static final int INDEX_USB = 2;
    private static final int INDEX_OTG = 3;
    private static final int INDEX_RFCalib = 4;

    // battery status
    private TextView mTextView_Battery;
    private Button mChangeBatteryStatusBtn;
    private static final String voltage_path = "/sys/class/power_supply/max17047_battery/uevent";
    private static final String VOLTAGE_DIRECTORY = "/sys/class/power_supply/";

    private static final String KEY_BATTERY_VOL_THRESHOLD_MIN = "BatteryVoltage_Threshold_MIN";
    private static final String KEY_BATTERY_VOL_THRESHOLD_MAX = "BatteryVoltage_Threshold_MAX";
    private static final String KEY_BATTERY_TEMP_THRESHOLD_MIN = "BatteryTemperature_Threshold_MIN";
    private static final String KEY_BATTERY_TEMP_THRESHOLD_MAX = "BatteryTemperature_Threshold_MAX";
    private static final String KEY_BATTERY_TMP = "BatteryTemperature";
    private static final String KEY_VOL_ERROR_LIMIT = "Voltage_Error_Limitation";
    private static final String KEY_TMP_ERROR_LIMIT = "Temperature_Error_Limitation";

    private float valueBatteryVoltageThresholdMin = 3500f;
    private float valueBatteryVoltageThresholdMax = 4350f;
    private float valueBatteryTemperatureThresholdMin = -10;
    private float valueBatteryTemperatureThresholdMax = 45;
    private float valueTmpErrorLimitation = 3f;

    private String sTotalMemorySize = "0 MB";
    private String sTotalNandFlashSize = "0 GB";
    private String sTotalSDCardhSize = "0 GB";

    int scale = 0;
    int plugType = 0;
    int status = 0;
    int health = 0;
    int temperature = 0;

    // sdcard RAMCapability
    private static final String PATH_EMMC_CAPACITY = "/sys/class/block/mmcblk0/size";
    private static final String KEY_RAMCapability = "RAMCapability";
    private static final String KEY_ROMCapability = "ROMCapability";
    private static final String KEY_InternalStorageCardCapbility = "InternalStorageCardCapability";
    private static final String KEY_ExternalStorageCardCapbility = "ExternalStorageCardCapability";
    private static final String KEY_RAM_ERROR_LIMITATION = "RAM_ERROR_LIMITATION";
    private static final String KEY_ROM_ERROR_LIMITATION = "ROM_ERROR_LIMITATION";
    private static final String KEY_STORAGE_CARD_ERROR_LIMITATION = "STORAGE_CARD_ERROR_LIMITATION";

    private float[] internalStorageMemInfos = new float[] { 0, 0 };
    private float[] externalStorageMemInfos = new float[] { 0, 0 };
    private float[] tempStorageMemInfos = new float[] { 0, 0 };
    private boolean internalStorageCardOK = false;
    private boolean externalStorageCardOK = false;

    private Properties properties;
    private float valueRamCapability = 1; // unit: G
    private float valueRomCapability = 0; // unit: G
    private float valueInternalStorageCardCapability = 0; // unit: G
    private float valueExternalStorageCardCapability = 0; // unit: G
    private float valueRamSizeErrorLimitation = 0.2f; // unit: G
    private float valueRomSizeErrorLimitation = 0.2f; // unit: G
    private float valueSdCardSizeErrorLimitation = 0.2f; // unit: G

    TextView mTextView_SdCard;
    private float mTotalSize = 0;
    private float mAvailSize = 0;
    private float mMemoryTotalSize = 0;
    private float mMemoryAvailSize = 0;
    private float mRamTotalSize = 0;
    private float mRamFreeSize = 0;
    private float mRamUsedSize = 0;
    private float mRomTotalSize = 0;
    private float mRomAvailSize = 0;
    private String mProduct;
    private String mSdPath = "";
    private static final String TEST_RESULT = "test_result";
    private String mTextString_Sdcard = "";
    private static final int FRESH = 1;

    // USB
    private TextView mcTestText_Usb;
    private boolean mUsbAvailable = false;

    // OTG
    private final String KEY_STATUS = "item_test_status";
    private Button passButton = null;
    private Button failButton = null;
    private TextView mTextView_OTG;
    private static final int READ_USB_DEVICE = 1;
    private boolean mAvailableOTG = false;

    // Handler Message
    private static final int MSG_CHECK_RESULT = 1;

    private UsbManager mUsbManager;
    private StorageManager mStorageManager;

    // Timer
    // private Timer mTimer_SDCard = null;
    // private Timer mTimer_OTG = null;
    // private Timer mTimer_CheckResult = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        properties = ((PropertiesConfParser) ConfigFileParseUtil
                .getConfParserConcrete(this,
                        AConfigFileParser.EXTENSION_PROPERTISE))
                .getProperties(isPcba);
        // get sdcard's configurations
        valueRamCapability = Float.parseFloat(properties.getProperty(
                KEY_RAMCapability, String.valueOf(valueRamCapability)));
        valueRomCapability = Float.parseFloat(properties.getProperty(
                KEY_ROMCapability, String.valueOf(valueRomCapability)));
        valueInternalStorageCardCapability = Float.parseFloat(properties
                .getProperty(KEY_InternalStorageCardCapbility,
                        String.valueOf(valueInternalStorageCardCapability)));
        valueExternalStorageCardCapability = Float.parseFloat(properties
                .getProperty(KEY_ExternalStorageCardCapbility,
                        String.valueOf(valueExternalStorageCardCapability)));
        valueRamSizeErrorLimitation = Float.parseFloat(properties.getProperty(
                KEY_RAM_ERROR_LIMITATION,
                String.valueOf(valueRamSizeErrorLimitation)));
        valueRomSizeErrorLimitation = Float.parseFloat(properties.getProperty(
                KEY_ROM_ERROR_LIMITATION,
                String.valueOf(valueRomSizeErrorLimitation)));
        valueSdCardSizeErrorLimitation = Float.parseFloat(properties
                .getProperty(KEY_STORAGE_CARD_ERROR_LIMITATION,
                        String.valueOf(valueSdCardSizeErrorLimitation)));

        // get battery's configurations
        valueBatteryVoltageThresholdMin = Float.parseFloat(properties
                .getProperty(KEY_BATTERY_VOL_THRESHOLD_MIN,
                        String.valueOf(valueBatteryVoltageThresholdMin)));
        valueBatteryVoltageThresholdMax = Float.parseFloat(properties
                .getProperty(KEY_BATTERY_VOL_THRESHOLD_MAX,
                        String.valueOf(valueBatteryVoltageThresholdMax)));
        valueBatteryTemperatureThresholdMin = Float.parseFloat(properties
                .getProperty(KEY_BATTERY_TEMP_THRESHOLD_MIN,
                        String.valueOf(valueBatteryTemperatureThresholdMin)));
        valueBatteryTemperatureThresholdMax = Float.parseFloat(properties
                .getProperty(KEY_BATTERY_TEMP_THRESHOLD_MAX,
                        String.valueOf(valueBatteryTemperatureThresholdMax)));
        valueTmpErrorLimitation = Float.parseFloat(properties.getProperty(
                KEY_TMP_ERROR_LIMIT, String.valueOf(valueTmpErrorLimitation)));

        setContentView(R.layout.sensor_gridview);
        initView();
        initInfoList();
        mGridAdapter = new GridAdapter(this, mInfoList);
        mGridView = (GridView) findViewById(R.id.gridview);
        mGridView.setAdapter(mGridAdapter);

        if (isSystemTest) {
            Intent intent = getIntent();
            confValue = intent.getStringExtra("value");
            initTestByConfig(confValue);
        } else {
            doBatteryStatusCheckTest = true;
            doSdCardReadTest = true;
            doUSBTest = true;  //modify by wangsm to false
            doOTGTest = true;
            doRFCalibStatus = true;
            mInfoList.get(INDEX_BatteryStatus).toTest = doBatteryStatusCheckTest;
            mInfoList.get(INDEX_SdCard).toTest = doSdCardReadTest;
            mInfoList.get(INDEX_USB).toTest = doUSBTest;
            mInfoList.get(INDEX_OTG).toTest = doOTGTest;
        }
        resultCharging = false;
        resultBatteryOK = false;
        resultSDCardOK = false;
        resultUsbOK = false;
        resultOtgOK = false;

        initStorageList();
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);

        // mStorageManager.registerListener(mStorageListener);
        // start test
        startTest();

        sTotalMemorySize = getTotalMemory();
        Log.d(TAG, "TotalMemorySize:" + sTotalMemorySize);

        sTotalNandFlashSize = getTotalNand();
        Log.d(TAG, "TotalNandFlashSize:" + sTotalNandFlashSize);

        TestExternStorage(ExistSDCard(), true);
    }

    @Override
    protected void initView() {
        super.initView();
        mSucBtn.requestFocus();//add by wangsm
/*        mSucBtn.setBackgroundColor(Color.argb(255, 255, 255, 0));
        mFailBtn.setBackgroundColor(Color.argb(255, 255, 255, 0));
        mRepeatBtn.setBackgroundColor(Color.argb(255, 255, 255, 0));*/
    }

    private void startTest() {
        if (doBatteryStatusCheckTest) {
            testBatteryStatusCheck();
        }
        if (doSdCardReadTest) {
            testSdcard();
        }
        if (doUSBTest) {
            testUSB();
        }
        if (doOTGTest) {
            testOTG();
            // String textString = "";
            // String cmd = "cat /sys/bus/usb/devices/*/product";
            // textString = callShellCmd_OTG(cmd);
            // if ("" != textString) {
            // mInfoList.get(INDEX_OTG).value =
            // getString(R.string.usb_status_host) + textString; // .put(TC_OTG,
            // getString(R.string.usb_status_host) + textString);
            // mInfoList.get(INDEX_OTG).isAvaliable = true;
            // resultOtgOK = true;
            // mGridAdapter.notifyDataSetChanged();
            // is_pass = true;
            // } else {
            // mInfoList.get(INDEX_OTG).value =
            // getString(R.string.insert_otg_cable); // .put(TC_OTG,
            // getString(R.string.insert_otg_cable));
            // mInfoList.get(INDEX_OTG).isAvaliable = false;
            // mGridAdapter.notifyDataSetChanged();
            // }

        }

    }

    private void testBatteryStatusCheck() {
        // mTextView_Battery = (TextView)findViewById(R.id.battery_status_txt);
        // mChangeBatteryStatusBtn =
        // (Button)findViewById(R.id.battery_status_btn);
        //
        // mChangeBatteryStatusBtn.setOnClickListener(new View.OnClickListener()
        // {
        //
        // @Override
        // public void onClick(View v) {
        // String tmp_voltage;
        // switch (v.getId()) {
        // case R.id.battery_status_btn:
        // tmp_voltage = getlevel();
        // if("Unavailable" != tmp_voltage) {
        // scale = Integer.parseInt(tmp_voltage);
        // setSummary(scale, plugType, status, health, temperature);
        // }
        // break;
        // }
        // }
        // });
    }

    private void testSdcard() {
        // mProduct = SystemProperties.get("ro.product.name");
        // boolean ismounted = Environment.getExternalStorageState().equals(
        // Environment.MEDIA_MOUNTED);
        // //mTextString = "";
        // if(!ismounted){
        // Log.i(TAG,
        // "getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT) = " +
        // getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT));
        // measureApproximateStorageAndRamAndRomAndCPU(false);
        // }
        // else{
        // Log.i(TAG, "ismounted =" + ismounted);
        // measureApproximateStorageAndRamAndRomAndCPU(true);
        //
        // }
    }

    private void testUSB() {

    }

    private void testOTG() {
        String textString = "";
        try {
            HashMap<String, UsbDevice> map = mUsbManager.getDeviceList();
            for (UsbDevice device : map.values()) {
                // Log.i(TAG, "dName: " + device.getDeviceName());
                // Log.i(TAG, "vid: " + device.getVendorId() + "\t pid: " +
                // device.getProductId());
                textString += device.getDeviceName() + "  Vendor:"
                        + Integer.toHexString(device.getVendorId()) + "  Id:"
                        + Integer.toHexString(device.getProductId());
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception" + e.getMessage());
            // Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
        }

        if ("" != textString) {
            mInfoList.get(INDEX_OTG).value = getString(R.string.usb_status_host)
                    + textString;
            resultOtgOK = true;
            is_pass = true;
        } else {

            mInfoList.get(INDEX_OTG).value = getString(R.string.insert_otg_cable);
            

        }
        
        if (resultOtgOK)
        {
            mInfoList.get(INDEX_OTG).isAvaliable = true;
        }else{
            mInfoList.get(INDEX_OTG).isAvaliable = false;
        }
        
        mGridAdapter.notifyDataSetChanged();

    }

    private void ReadRFCalibStatus() {

        // SystemProperties.get("gsm.calib");
        StringBuilder mStringBuilder = new StringBuilder();

        // String sRFCalib=System.getProperty("gsm.calib");
        // String sRFCalib = SystemProperties.get("gsm.calib","0");
        Boolean sRFCalib = SystemProperties.getBoolean("gsm.calib", false);

        Log.d("jiale RFtest", "sRFCalib =" + sRFCalib);
        if (sRFCalib) {
            resultRFCalibOK = true;
            mStringBuilder.append("OK");
            mInfoList.get(INDEX_RFCalib).value = getString(R.string.RFHadCalib);
        } else {
            resultRFCalibOK = false;
            mInfoList.get(INDEX_RFCalib).isRedBg = true;
            mStringBuilder.append("FAIL");
            mInfoList.get(INDEX_RFCalib).value = getString(R.string.RFDoNotCalib);
        }

        // mInfoList.get(INDEX_RFCalib).value = mStringBuilder.toString(); //
        // .put(TC_BatteryStatusCheck, mStringBuilder.toString());
        mInfoList.get(INDEX_RFCalib).isAvaliable = true;
        mGridAdapter.notifyDataSetChanged();
    }

    private void initInfoList() {

        ItemInfo batterstatusInfo = ItemInfo.getInstance(
                getString(R.string.ComprehensiveBatteryStatusCheck)/*
                                                                     * nameMapping.
                                                                     * get(
                                                                     * TC_BatteryStatusCheck
                                                                     * )
                                                                     */, "",
                doBatteryStatusCheckTest, false, false);
        ItemInfo sdcard = ItemInfo.getInstance(
                getString(R.string.ComprehensiveStorage)/*
                                                         * nameMapping.get(TC_SdCard
                                                         * )
                                                         */, "",
                doSdCardReadTest, false, false);
        ItemInfo usbInfo = ItemInfo.getInstance(
                getString(R.string.ComprehensiveUSB)/*
                                                     * nameMapping.get (TC_USB)
                                                     */, "", doUSBTest, false,
                false);
        ItemInfo otgInfo = ItemInfo.getInstance(
                getString(R.string.ComprehensiveOTG)/*
                                                     * nameMapping.get (TC_OTG)
                                                     */, "", doOTGTest, false,
                false);
        ItemInfo RFCalibInfo = ItemInfo.getInstance(
                getString(R.string.ComprehensiveRFCalib), "", doRFCalibStatus,
                false, false);

        mInfoList.add(batterstatusInfo); // index = 0;
        mInfoList.add(sdcard); // index = 1;
        mInfoList.add(usbInfo); // index = 2;//remove by wangsm
        mInfoList.add(otgInfo); // index = 3;
        //mInfoList.add(RFCalibInfo); // index = 4;
    }

    private Handler mHandler_CheckResult = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_CHECK_RESULT:
                // ComprehensiveTest.this.checkResult();
                break;

            default:
                break;
            }
        }

    };

    private void checkResult() {
        if ((!mInfoList.get(INDEX_BatteryStatus).toTest || mInfoList
                .get(INDEX_BatteryStatus).toTest
                && mInfoList.get(INDEX_BatteryStatus).isAvaliable
                && !mInfoList.get(INDEX_BatteryStatus).isRedBg)
                && (!mInfoList.get(INDEX_SdCard).toTest || mInfoList
                        .get(INDEX_SdCard).toTest
                        && mInfoList.get(INDEX_SdCard).isAvaliable
                        && !mInfoList.get(INDEX_SdCard).isRedBg)
                        //remove by wangsm
/*                && (!mInfoList.get(INDEX_USB).toTest || mInfoList
                        .get(INDEX_USB).toTest
                        && mInfoList.get(INDEX_USB).isAvaliable)*/
                /*&& (!mInfoList.get(INDEX_OTG).toTest || mInfoList
                        .get(INDEX_OTG).toTest
                        && mInfoList.get(INDEX_OTG).isAvaliable)*/) {
            mSucBtn.setVisibility(View.VISIBLE);
            mSucBtn.setEnabled(true);
            // mSucBtn.setBackgroundColor(Color.WHITE);
        //    mSucBtn.setBackgroundColor(Color.argb(255, 255, 255, 0)); //remove by wangsm
            // mFailBtn.setEnabled(false);
            // mFailBtn.setBackgroundColor(Color.GRAY);
            // mFailBtn.setBackgroundColor(Color.argb(255, 153, 153, 255));
            //mFailBtn.setVisibility(View.INVISIBLE); //remove by wangsm
        } else {
            // mSucBtn.setEnabled(false);
            // mSucBtn.setBackgroundColor(Color.GRAY);
            // mSucBtn.setBackgroundColor(Color.argb(255, 153, 153, 255));
            mSucBtn.setVisibility(View.INVISIBLE);

            mFailBtn.setVisibility(View.VISIBLE);
            mFailBtn.setEnabled(true);
            //mFailBtn.setBackgroundColor(Color.argb(255, 255, 255, 0));  //remove by wangsm
        }
    }

    // private void startCheck() {
    // mTimer_CheckResult = new Timer();
    // TimerTask task = new TimerTask() {
    //
    // @Override
    // public void run() {
    // // TODO Auto-generated method stub
    // mHandler_CheckResult.sendEmptyMessage(MSG_CHECK_RESULT);
    // }
    // };
    // mTimer_CheckResult.schedule(task, 500, 1000);
    // }

    private void initTestByConfig(String config) {
        if (config == null || config.trim().length() == 0)
            return;

        Log.i("tangjun comprehensive test", "config = " + config);

        String[] configs = config.split(";");
        for (String conf : configs) {
            String[] items = conf.split("=");

            // overall sensors' switch
            if (items.length == 1) {
                if (items[0].equals("0")) {
                    // Don't test any Sensor!
                    break;
                }
                continue;
            }

            // single sensor's switch
            boolean doTest = false;
            if (items[1].equals("1")) {
                doTest = true;
            }

            if (items[0].equals(TC_BatteryStatusCheck)) {
                doBatteryStatusCheckTest = doTest;
                mInfoList.get(INDEX_BatteryStatus).toTest = doBatteryStatusCheckTest;
            } else if (items[0].equals(TC_SdCard)) {
                doSdCardReadTest = doTest;
                mInfoList.get(INDEX_SdCard).toTest = doSdCardReadTest;
            } 
            //remove by wangsm
            /*else if (items[0].equals(TC_USB)) {
                doUSBTest = doTest;
                mInfoList.get(INDEX_USB).toTest = doUSBTest;
            } else if (items[0].equals(TC_OTG)) {
                doOTGTest = doTest;
                mInfoList.get(INDEX_OTG).toTest = doOTGTest;
            } */

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // register BroadcastReceiver for Battery status
        if (doBatteryStatusCheckTest) {
            IntentFilter mIntentFilter = new IntentFilter();
            mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
            registerReceiver(mReceiverBatteryInfo, mIntentFilter, "permission.CIT_ALLOW_BROADCAST", null);
        }

        // MicroSD
        // register BroadcastReceiver for MicroSD
        if (doSdCardReadTest) {
            IntentFilter intentFilterSD = new IntentFilter();
            intentFilterSD.addAction(Intent.ACTION_MEDIA_MOUNTED);
            intentFilterSD.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
            intentFilterSD.addAction(Intent.ACTION_MEDIA_EJECT);
            intentFilterSD.addDataScheme("file");
            registerReceiver(mReceiverPlugSdcard, intentFilterSD, "permission.CIT_ALLOW_BROADCAST", null);

            // mTimer_SDCard = new Timer();
            // mTimer_SDCard.schedule(new TimerTask() {
            //
            // @Override
            // public void run() {
            // //mHandler_SdCard.sendEmptyMessage(FRESH);
            // }
            //
            // }, 1000, 1000);
        }

        // register BroadcastReceiver for USB
        if (doUSBTest) {
            IntentFilter intentFilterUsb = new IntentFilter();
            intentFilterUsb.addAction(UsbManager.ACTION_USB_STATE);
            registerReceiver(mReceiverUsb, intentFilterUsb, "permission.CIT_ALLOW_BROADCAST", null);
        }

        if (doOTGTest) {
            IntentFilter mIntentFilter = new IntentFilter();
            mIntentFilter
                    .addAction("android.hardware.usb.action.USB_DEVICE_ATTACHED");
            mIntentFilter
                    .addAction("android.hardware.usb.action.USB_DEVICE_DETACHED");
            mIntentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
            // mIntentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
            // mIntentFilter.addAction(UsbManager.ACTION_USB_STATE);
            // mIntentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
            // mIntentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
            // mIntentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
            registerReceiver(mReceiverOTG, mIntentFilter, "permission.CIT_ALLOW_BROADCAST", null);
        }

        // OTG
        // if (doOTGTest) {
        // mTimer_OTG = new Timer();
        // mTimer_OTG.schedule(new TimerTask() {
        //
        // @Override
        // public void run() {
        // mHandler_OTG.sendEmptyMessage(READ_USB_DEVICE);
        // }
        //
        // }, 200, 1000);
        // }


        // check result
        // startCheck();

    }

    private BroadcastReceiver mReceiverUsb = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(UsbManager.ACTION_USB_STATE)) {
                mUsbAvailable = intent.getBooleanExtra(
                        UsbManager.USB_CONNECTED, false);
            }
            if (mUsbAvailable) {
                // mcTestText_Usb.setText(getString(R.string.usb_status_device)
                // + "\n"
                // + getString(R.string.usb_ok));
                mInfoList.get(INDEX_USB).value = getString(R.string.usb_status_device)
                        + "\n" + getString(R.string.usb_ok); 
                
                resultUsbOK = true;
                is_pass = true;
            } else {
                // mcTestText_Usb.setText(getString(R.string.insert_usb_cable));
                mInfoList.get(INDEX_USB).value = getString(R.string.insert_usb_cable);                
                
            }
            
            if (resultUsbOK)
            {
                mInfoList.get(INDEX_USB).isAvaliable = true;
            }else{
                mInfoList.get(INDEX_USB).isAvaliable = false;
            }
            
            mGridAdapter.notifyDataSetChanged();
                
        }
    };

    private BroadcastReceiver mReceiverOTG = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // Toast.makeText(getApplicationContext(),action,Toast.LENGTH_SHORT).show();
            if (action
                    .equals("android.hardware.usb.action.USB_DEVICE_ATTACHED")
                    || action
                            .equals("android.hardware.usb.action.USB_DEVICE_DETACHED")) {
                testOTG();
                // mHandler_OTG.sendEmptyMessage(READ_USB_DEVICE);
            }
        }
    };

    // private StorageEventListener mStorageListener = new
    // StorageEventListener() {
    // @Override
    // public void onStorageStateChanged(String path, String oldState, String
    // newState) {
    // final boolean on = newState.equals(Environment.MEDIA_SHARED);
    // }
    // };

    protected void onPause() {
        super.onPause();
        if (doBatteryStatusCheckTest) {
            unregisterReceiver(mReceiverBatteryInfo);
        }
        if (doUSBTest) {
            unregisterReceiver(mReceiverUsb);
        }
        if (doOTGTest) {
            unregisterReceiver(mReceiverOTG);
        }
        if (doSdCardReadTest) {
            unregisterReceiver(mReceiverPlugSdcard);
        }
        // if (mTimer_SDCard != null) {
        // mTimer_SDCard.cancel();
        // }
        // if (mTimer_OTG != null) {
        // mTimer_OTG.cancel();
        // }
        // if (mTimer_CheckResult != null) {
        // mTimer_CheckResult.cancel();
        // }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    // #######################################################
    // # BatteryStatus #
    // #######################################################

    private BroadcastReceiver mReceiverBatteryInfo = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            String action = intent.getAction();

            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {

                scale = intent.getIntExtra("voltage", 0);

                plugType = intent.getIntExtra("plugged", 0);
                status = intent.getIntExtra("status",
                        BatteryManager.BATTERY_STATUS_UNKNOWN);
                health = intent.getIntExtra("health",
                        BatteryManager.BATTERY_HEALTH_UNKNOWN);
                temperature = intent.getIntExtra("temperature",
                        BatteryManager.BATTERY_HEALTH_UNKNOWN);
                setSummary(scale, plugType, status, health, temperature);
            }

        }

    };

    private String getlevel() {
        String tempStr = "Unavailable";
        int pos = 0;
        int value = 0;
        Log.i(TAG, "pos = " + pos);
        String target = "POWER_SUPPLY_VOLTAGE_NOW=";
        try {
            File voltageFile = new File(voltage_path);
            if (voltageFile.exists()) {
                BufferedReader reader = new BufferedReader(new FileReader(
                        voltage_path));
                try {
                    do {
                        tempStr = reader.readLine();
                        Log.i(TAG, "tempStr: " + tempStr);
                        pos = tempStr.indexOf(target);
                        Log.i(TAG, "pos = " + pos);
                    } while (pos != 0 && tempStr != null);
                    pos = pos + target.length();
                    tempStr = tempStr.substring(pos, pos + 4);
                } finally {
                    reader.close();
                }
            } else {
                File directory = new File(VOLTAGE_DIRECTORY);
                File[] files = directory.listFiles();
                for (File file : files) {
                    Log.i(TAG, "file = " + file.getName());
                    if (file.getName().contains("battery")) {
                        String tmpDir = VOLTAGE_DIRECTORY + file.getName();
                        directory = new File(tmpDir);
                        files = directory.listFiles();
                        for (File subFile : files) {
                            Log.i(TAG, "subfile = " + subFile.getName());
                            if (subFile.getName().equals("uevent")) {
                                Log.i(TAG, "subfile2 = " + tmpDir + "/"
                                        + "uevent");
                                BufferedReader reader = new BufferedReader(
                                        new FileReader(tmpDir + "/" + "uevent"));
                                try {
                                    do {
                                        tempStr = reader.readLine();
                                        Log.i(TAG, "tempStr: " + tempStr);
                                        pos = tempStr.indexOf(target);
                                        Log.i(TAG, "pos = " + pos);
                                    } while (pos != 0 && tempStr != null);
                                    pos = pos + target.length();
                                    tempStr = tempStr.substring(pos, pos + 4);
                                } finally {
                                    reader.close();
                                }
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            return tempStr;
        } catch (IOException e) {
            return "Unavailable";
        }
    }

    private void setSummary(int batteryV, int plugType, int status, int health,
            int temperature) {
        String statusString;
        String healthString;
        if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
            resultCharging = true;
            statusString = this
                    .getString(R.string.SERVICEMENU_BATTERY_STATUS_CHARGING_TXT);
            if (plugType > 0) {
                statusString = statusString
                        + " "
                        + this.getString((plugType == BatteryManager.BATTERY_PLUGGED_AC) ? R.string.SERVICEMENU_BATTERY_STATUS_CHARGING_AC_TXTB
                                : R.string.SERVICEMENU_BATTERY_STATUS_CHARGING_USB_TXT);
                is_pass = true;
            }
        } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
            statusString = this
                    .getString(R.string.SERVICEMENU_BATTERY_STATUS_DISCHARGING_TXT);
        } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
            statusString = this
                    .getString(R.string.SERVICEMENU_BATTERY_STATUS_NOT_CHARGING_TXT);
        } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
            statusString = this
                    .getString(R.string.SERVICEMENU_BATTERY_STATUS_FULL_TXT);
            is_pass = true;
        } else {
            statusString = this
                    .getString(R.string.SERVICEMENU_BATTERY_STATUS_UNKNOWN_TXT);
        }

        if (health == BatteryManager.BATTERY_HEALTH_GOOD) {
            healthString = this
                    .getString(R.string.SERVICEMENU_BATTERY_HEALTH_GOOD_TXT);
        } else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT) {
            healthString = this
                    .getString(R.string.SERVICEMENU_BATTERY_HEALTH_OVERHEAT_TXT);
        } else if (health == BatteryManager.BATTERY_HEALTH_DEAD) {
            healthString = this
                    .getString(R.string.SERVICEMENU_BATTERY_HEALTH_DEAD_TXT);
        } else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE) {
            healthString = this
                    .getString(R.string.SERVICEMENU_BATTERY_HEALTH__OVER_VOLTAGE_TXT);
        } else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE) {
            healthString = this
                    .getString(R.string.SERVICEMENU_BATTERY_HEALTH_UNSPECIFIED_FAILURE_TXT);
        } else {
            healthString = this
                    .getString(R.string.SERVICEMENU_BATTERY_HEALTH_UNKNOWN_TXT);
        }
        resultBatteryOK = true;
        StringBuilder mStringBuilder = new StringBuilder();
        mStringBuilder
                .append(getString(R.string.SERVICEMENU_BATTERY_VOLTAGE_TXT));
        mStringBuilder.append(batteryV);
        mStringBuilder.append("mV");
        if (isSystemTest) {
            if (!checkVoltage(batteryV)) {
                mStringBuilder
                        .append(getString(R.string.ComprehensiveInvalidVoltage));
                mInfoList.get(INDEX_BatteryStatus).isRedBg = true;
                resultBatteryOK = false;
            }
        } else {

        }
        mStringBuilder.append("\n");
        mStringBuilder
                .append(getString(R.string.SERVICEMENU_BATTERY_STATUS_TXT));
        mStringBuilder.append(statusString);
        mStringBuilder.append("\n");
        // drop battery health status
        /*
         * mStringBuilder.append(getString(R.string.SERVICEMENU_BATTERY_HEALTH_TXT
         * )); mStringBuilder.append(healthString); mStringBuilder.append("\n");
         */
        mStringBuilder
                .append(getString(R.string.SERVICEMENU_BATTERY_TEMPERATURE_TXT));
        float convertedTemperature = (float) temperature / 10.0f;
        mStringBuilder.append(convertedTemperature);
        mStringBuilder
                .append(getString(R.string.SERVICEMENU_BATTERY_TEMPERATURE_UNIT_TXT));
        if (!checkTemperature(convertedTemperature)) {
            mStringBuilder
                    .append(getString(R.string.ComprehensiveInvalidTemperature));
            mInfoList.get(INDEX_BatteryStatus).isRedBg = true;
            resultBatteryOK = false;
        }
        mStringBuilder.append("\n");
        if (is_pass) {
            mStringBuilder
                    .append(getString(R.string.SERVICEMENU_BATTERY_TEMPERATURE_OK_TXT)
                            + "\n");
        }
        // mTextView_Battery.setText(mStringBuilder.toString());
        mInfoList.get(INDEX_BatteryStatus).value = mStringBuilder.toString(); // .put(TC_BatteryStatusCheck,
                                                                                // mStringBuilder.toString());
        if (resultCharging) {
            mInfoList.get(INDEX_BatteryStatus).isRedBg = false;
            resultBatteryOK = true;
        } else {
            mInfoList.get(INDEX_BatteryStatus).isRedBg = true;
            resultBatteryOK = false;
        }
        mInfoList.get(INDEX_BatteryStatus).isAvaliable = true;
        mGridAdapter.notifyDataSetChanged();
    }

    private boolean checkVoltage(float v) {
        System.out.println("tangjun check battery voltage: min="
                + valueBatteryVoltageThresholdMin + ",max="
                + valueBatteryVoltageThresholdMax);
        return v >= valueBatteryVoltageThresholdMin
                && v <= valueBatteryVoltageThresholdMax;
    }

    private boolean checkTemperature(float t) {
        System.out.println("tangjun check battery voltage: min="
                + valueBatteryTemperatureThresholdMin + ",max="
                + valueBatteryTemperatureThresholdMax);
        return t >= valueBatteryTemperatureThresholdMin
                && t <= valueBatteryTemperatureThresholdMax;
    }

    // #######################################################
    // # MicroSD #
    // #######################################################

    final BroadcastReceiver mReceiverPlugSdcard = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            Log.d(TAG, "enter onReceive " + intent.getAction());
            // Log.d(TAG, "getDataString: " + intent.getDataString());

            if (intent.getDataString().contains("sdcard1")) {
                if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) {
                    ExistSDCard();
                    TestExternStorage(true, false);
                } else {
                    TestExternStorage(false, false);
                }
            }

            // TestExternStorage(ExistSDCard(),false);

            // if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) {
            // mSdPath = intent.getData().getPath();
            // measureApproximateStorageAndRamAndRomAndCPU(true);
            // mInfoList.get(INDEX_SdCard).isAvaliable = true;
            // // resultSDCardOK = true;
            // } else if
            // (intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
            // measureApproximateStorageAndRamAndRomAndCPU(false);
            // mInfoList.get(INDEX_SdCard).isAvaliable = false;
            //
            // } else {
            // }

            // if (doOTGTest){
            // testOTG();
            // }
        }
    };

    private String internalStoragePath = "";
    private String externalStoragePath = "";
    private String[] storageList;

    private void initStorageList() {
        storageList = SDCardUtil.getStorageList(this);
        if (storageList != null) {
            for (String storageDir : storageList) {
                if (storageDir.contains("emulated")) {
                    internalStoragePath = storageDir;
                } else if (storageDir.contains("sdcard1")) {
                    externalStoragePath = storageDir;
                } else {
                    // do nothing
                }
            }
        }
    }

    private float[] readStorageInfo(String filepath) {
        float mTotalSize = 0;
        float mAvailableSize = 0;
        tempStorageMemInfos[0] = mTotalSize;
        tempStorageMemInfos[1] = mAvailableSize;
        File file = new File(filepath);
        StatFs stat = null;
        if (file.exists()) {
            stat = new StatFs(filepath);
        } else {
            return tempStorageMemInfos;
        }
        final float blockSize = stat.getBlockSize();
        final float totalBlocks = stat.getBlockCount();
        final float availableBlocks = stat.getAvailableBlocks();

        mTotalSize = totalBlocks * blockSize;
        mAvailableSize = availableBlocks * blockSize;

        mTotalSize = mTotalSize / (1024 * 1024 * 1024);
        mAvailableSize = mAvailableSize / (1024 * 1024);

        tempStorageMemInfos[0] = mTotalSize;
        tempStorageMemInfos[1] = mAvailableSize;

        System.out.println("mTotalSize=" + mTotalSize + "; mAvailableSize="
                + mAvailableSize);

        return tempStorageMemInfos;
    }

    private boolean checkCapability(float expect, float actual, float error) {
        System.out.println("tangjun check capability: expect=" + expect
                + ", actual=" + actual + ", error=" + error);
        return Math.abs(expect - actual) <= error;
    }

    Handler mHandler_SdCard = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == FRESH) {
                // boolean ismounted =
                // Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
                // Log.i(TAG, "ismounted " + ismounted);
                // if(ismounted) {
                // measureApproximateStorageAndRamAndRomAndCPU(true);
                // } else {
                // measureApproximateStorageAndRamAndRomAndCPU(false);
                // }
                mTextString_Sdcard = "";
                // 1. read ram and rom and cpu
                measureApproximateRamAndRomAndCPU();
                // 2. read internal card
                /*
                 * internalStorageMemInfos =
                 * readStorageInfo(internalStoragePath); internalStorageCardOK =
                 * isOKStorageCard(internalStorageMemInfos); if
                 * (!internalStorageCardOK) { mTextString_Sdcard +=
                 * "请插入内部存储卡\n"; if (isSystemTest) { // system test if
                 * (!checkCapability(valueInternalStorageCardCapability,
                 * Util.dealDecimals(internalStorageMemInfos[0], 1),
                 * valueSdCardSizeErrorLimitation)) {
                 * mInfoList.get(INDEX_SdCard).isRedBg = true; } } else {//
                 * single test
                 * 
                 * } } else { if (internalStorageMemInfos[1] > 1024) {
                 * internalStorageMemInfos[1] /= 1024; mTextString_Sdcard +=
                 * "内部存储卡: 内存总数： " +
                 * Util.dealDecimals(internalStorageMemInfos[0], 1) + "G, 空闲：" +
                 * Util.dealDecimals(internalStorageMemInfos[1], 1) + "G\n"; }
                 * else { mTextString_Sdcard += "内部存储卡: 内存总数： " +
                 * Util.dealDecimals(internalStorageMemInfos[0], 1) + "G, 空闲：" +
                 * Util.dealDecimals(internalStorageMemInfos[1], 1) + "M\n"; }
                 * if (isSystemTest) { // system test need to check
                 * configuration if
                 * (!checkCapability(valueInternalStorageCardCapability,
                 * Util.dealDecimals(internalStorageMemInfos[0], 1),
                 * valueSdCardSizeErrorLimitation)) {
                 * mInfoList.get(INDEX_SdCard).isRedBg = true;
                 * mTextString_Sdcard += MSG_INTERNAL_SDCARD_BEYOND_ERROR_LIMIT;
                 * } } else {
                 * 
                 * } }
                 */
                // 3. read external card
                externalStorageMemInfos = readStorageInfo(externalStoragePath);
                externalStorageCardOK = isOKStorageCard(externalStorageMemInfos);
                if (!externalStorageCardOK) {
                    mTextString_Sdcard += getString(R.string.ComprehensivePluginTFCard);
                    if (isSystemTest) { // system test need to check
                                        // configuration
                        if (!checkCapability(
                                valueInternalStorageCardCapability,
                                Util.dealDecimals(externalStorageMemInfos[0], 1),
                                valueSdCardSizeErrorLimitation)) {
                            mInfoList.get(INDEX_SdCard).isRedBg = true;
                        }
                    } else {

                    }
                } else {
                    if (externalStorageMemInfos[1] > 1024) {
                        externalStorageMemInfos[1] /= 1024;
                        mTextString_Sdcard += getString(R.string.ComprehensiveTFCardTitel)
                                + Util.dealDecimals(externalStorageMemInfos[0],
                                        1)/*
                                         * + "G, 空闲：" +
                                         * Util.dealDecimals(externalStorageMemInfos
                                         * [1], 1)
                                         */+ "G\n";
                    } else {
                        mTextString_Sdcard += getString(R.string.ComprehensiveTFCardTitel)
                                + Util.dealDecimals(externalStorageMemInfos[0],
                                        1)/*
                                         * + "G, 空闲：" +
                                         * Util.dealDecimals(externalStorageMemInfos
                                         * [1], 1)
                                         */+ "M\n";
                    }
                    if (isSystemTest) {
                        if (!checkCapability(
                                valueExternalStorageCardCapability,
                                Util.dealDecimals(externalStorageMemInfos[0], 1),
                                valueSdCardSizeErrorLimitation)) {
                            mInfoList.get(INDEX_SdCard).isRedBg = true;
                            mTextString_Sdcard += getString(R.string.ComprehensiveBigErrorTFCard);
                        }
                    } else {

                    }
                }
                // 4. judge result
                if (/* internalStorageCardOK && */externalStorageCardOK
                        && !mInfoList.get(INDEX_SdCard).isRedBg) {
                    mInfoList.get(INDEX_SdCard).isAvaliable = true;
                    resultSDCardOK = true;
                }
                mInfoList.get(INDEX_SdCard).value = mTextString_Sdcard;
                mGridAdapter.notifyDataSetChanged();
            }

        }

    };

    private boolean isOKStorageCard(float[] storageMemInfos) {
        if (storageMemInfos == null || storageMemInfos.length != 2) {
            return false;
        }
        return ((storageMemInfos[0] == 0) && (storageMemInfos[1] == 0)) ? false
                : true;
    }

    private void measureApproximateStorageAndRamAndRomAndCPU(
            boolean needApproximateStorage) {
        synchronized (this) {

            mTextString_Sdcard = "";
            measureApproximateRamAndRomAndCPU();
            if (!needApproximateStorage)
                mTextString_Sdcard = mTextString_Sdcard
                        + getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT)
                        + "\n";
            measureApproximateStorage(needApproximateStorage);

            // mTextView_SdCard.setText(mTextString);
            mInfoList.get(INDEX_SdCard).value = mTextString_Sdcard; // .put(TC_SdCard,
                                                                    // mTextString_Sdcard);
            mGridAdapter.notifyDataSetChanged();
        }
    }

    private void callShellCommand_Sdcard(String cmd) {
        Log.e(TAG, "########### cmd =" + cmd);
        try {
            Process p = Runtime.getRuntime().exec(
                    new String[] { "sh", "-c", cmd });
            InputStream is = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String tmp = "";
            while ((tmp = br.readLine()) != null) {
                Log.i("yjc", tmp);
                if (tmp.contains("fat")) {
                    String[] tmpStrs = tmp.split(" ");
                    mSdPath = tmpStrs[1];

                }
            }
            br.close();

            InputStream eis = p.getErrorStream();
            InputStreamReader eisr = new InputStreamReader(eis);
            BufferedReader ebr = new BufferedReader(eisr);

            while ((tmp = ebr.readLine()) != null) {
                Log.e("yjc", tmp);
            }
            ebr.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void measureApproximateStorage(boolean need) {
        if (!need)
            return;
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
                .getPath());
        Log.i(TAG, Environment.getExternalStorageDirectory().getPath());

        // sd card ext
        if (Environment.getExternalStorageDirectory().getPath()
                .equals("/storage/emulated/0")) {
            File file = null;

            file = new File("/mnt/sdcard_ext");
            if (file.exists()) {
                stat = new StatFs("/mnt/sdcard_ext");
            } else {
                if (!mSdPath.equals("")) {
                    file = new File(mSdPath);
                    if (file.exists()) {
                        stat = new StatFs(mSdPath);
                    }
                } else {
                    callShellCommand_Sdcard("mount");
                    mSdPath = "/storage/"
                            + mSdPath.substring(mSdPath.lastIndexOf("/") + 1);
                    file = new File(mSdPath);
                    if (file.exists()) {
                        stat = new StatFs(mSdPath);
                    }
                }
            }
        }
        Log.i(TAG, "mSdPath == " + mSdPath);
        final float blockSize = stat.getBlockSize();
        final float totalBlocks = stat.getBlockCount();
        final float availableBlocks = stat.getAvailableBlocks();

        mTotalSize = totalBlocks * blockSize;
        mAvailSize = availableBlocks * blockSize;

        mTotalSize = mTotalSize / (1024 * 1024 * 1024);
        mAvailSize = mAvailSize / (1024 * 1024);
        if (mTotalSize == 0) {
            Log.i(TAG, "mTotalSize == 0");
            // tv.setText(getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT));
            mTextString_Sdcard += getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT);
            return;
        }
        if (mTotalSize == mRomTotalSize) {
            Log.i(TAG, "mTotalSize == mRomTotalSize");
            mTextString_Sdcard += getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT);
            return;
        }
        is_pass = true;
        if (mAvailSize > 1024) {
            mAvailSize = mAvailSize / (1024);
            // tv.setText("External SD Total size is ="+ mTotalSize
            // +"G AvailSize is ="+mAvailSize+"G");
            mTextString_Sdcard += getString(R.string.SERVICEMENU_SDCARD_TOTALSIZE_TXT)
                    + Util.dealDecimals(mTotalSize, 0)
                    + "G "
                    + getString(R.string.SERVICEMENU_SDCARD_AVAILSIZE_TXT)
                    + Util.dealDecimals(mAvailSize, 1) + "G";
        } else {
            // tv.setText("External SD Total size is ="+ mTotalSize
            // +"G AvailSize is ="+mAvailSize+"M");
            mTextString_Sdcard += getString(R.string.SERVICEMENU_SDCARD_TOTALSIZE_TXT)
                    + Util.dealDecimals(mTotalSize, 0)
                    + "G "
                    + getString(R.string.SERVICEMENU_SDCARD_AVAILSIZE_TXT)
                    + Util.dealDecimals(mAvailSize, 1) + "M";
        }

    }

    private void measureApproximateRamAndRomAndCPU() {
        // Ram
        String strRamPath = "/proc/meminfo";
        try {

            FileReader fr = new FileReader(strRamPath);
            BufferedReader br = new BufferedReader(fr, 8192);
            String memTotal = br.readLine().replace(" ", "");
            String[] memTotals = memTotal.split(":");

            String memFree = br.readLine().replace(" ", "");
            String[] memFrees = memFree.split(":");

            mRamTotalSize = (float) Integer.parseInt(memTotals[1].substring(0,
                    memTotals[1].length() - 2));
            mRamFreeSize = (float) Integer.parseInt(memFrees[1].substring(0,
                    memFrees[1].length() - 2));
            ;
            mRamUsedSize = mRamTotalSize - mRamFreeSize;
            mTextString_Sdcard += getString(R.string.SERVICEMENU_RAM_TOTALSIZE_TXT)
                    + Util.dealDecimals(mRamTotalSize / (1024f * 1024f), 1)
                    + "G  "/*
                             * + getString(R.string.SERVICEMENU_RAM_FREE_TXT) +
                             * Util.dealDecimals(mRamFreeSize/(1024f * 1024f),
                             * 1) +"G " +
                             * getString(R.string.SERVICEMENU_RAM_USED_TXT) +
                             * Util.dealDecimals(mRamUsedSize/(1024f * 1024f),
                             * 1) + "G"
                             */+ "\n";
            if (isSystemTest) {
                if (!checkCapability(valueRamCapability, mRamTotalSize
                        / (1024f * 1024f), valueRamSizeErrorLimitation)) {
                    mInfoList.get(INDEX_SdCard).isRedBg = true;
                    mTextString_Sdcard += getString(R.string.ComprehensiveBigErrorMemory);
                }
            } else {

            }

            fr.close();

            // Log.i("meilianggang", memFrees[0] + "-" +
            // memFrees[1].substring(0, memFrees[1].length()-2));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Rom

        // final StatFs stat = new
        // StatFs(Environment.getDataDirectory().getPath()); // /data
        // System.out.println("tangjun ROM path=" +
        // Environment.getDataDirectory().getAbsolutePath());
        //
        // final float blockSize = stat.getBlockSize();
        // final float totalBlocks = stat.getBlockCount();
        // final float availableBlocks = stat.getAvailableBlocks();
        //
        // mRomTotalSize = totalBlocks * blockSize;
        // mRomAvailSize = availableBlocks * blockSize;
        //
        // mRomTotalSize = mRomTotalSize/(1024*1024*1024);
        // mRomAvailSize = mRomAvailSize/(1024*1024);
        mRomTotalSize = Util.dealDecimals(read_eMMC_size(), 2);

        if (mRomAvailSize > 1024) {
            mRomAvailSize = mRomAvailSize / (1024);
            mTextString_Sdcard += getString(R.string.SERVICEMENU_ROM_TOTALSIZE_TXT)
                    + Util.dealDecimals(mRomTotalSize, 0) + "G "/*
                                                                 * +
                                                                 * getString(R.
                                                                 * string.
                                                                 * SERVICEMENU_ROM_AVAIL_TXT
                                                                 * ) +
                                                                 * Util.dealDecimals
                                                                 * (
                                                                 * mRomAvailSize
                                                                 * , 1) + "G"
                                                                 */+ "\n";
            // Log.i("meilianggang","total size " + mRomTotalSize + "G" +
            // " avail size " + mRomAvailSize + "G");
        } else {
            // Log.i("meilianggang","total size " + mRomTotalSize + "G" +
            // " avail size " + mRomAvailSize + "M");
            mTextString_Sdcard += getString(R.string.SERVICEMENU_ROM_TOTALSIZE_TXT)
                    + Util.dealDecimals(mRomTotalSize, 0) + "G "/*
                                                                 * +
                                                                 * getString(R.
                                                                 * string.
                                                                 * SERVICEMENU_ROM_AVAIL_TXT
                                                                 * ) +
                                                                 * Util.dealDecimals
                                                                 * (
                                                                 * mRomAvailSize
                                                                 * , 1) + "M"
                                                                 */+ "\n";
        }
        if (isSystemTest) {
            if (!checkCapability(valueRomCapability,
                    Util.dealDecimals(mRomTotalSize, 0),
                    valueRomSizeErrorLimitation)) {
                mInfoList.get(INDEX_SdCard).isRedBg = true;
                mTextString_Sdcard += getString(R.string.ComprehensiveBigErrorEMMC);
            }
        } else {

        }

    }

    private float read_eMMC_size() {
        float size = 0.0f;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(PATH_EMMC_CAPACITY));
            String sizeStr = "";
            if (null != (sizeStr = br.readLine())) {
                size = Float.parseFloat(sizeStr);
                size = size / 2 / 1024 / 1024;
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NumberFormatException e) {
            // TODO: handle exception
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return size;
    }

    public boolean ac_ispass() {
        return is_pass;
    }

    // #######################################################
    // # OTG #
    // #######################################################

    Handler mHandler_OTG = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // DoingMessage = true;
            if (msg.what == READ_USB_DEVICE) {

                String textString = "";
                String cmd = "cat /sys/bus/usb/devices/*/product";
                textString = callShellCmd_OTG(cmd);
                if ("" != textString) {
                    // mTextView_OTG.setText(getString(R.string.usb_status_host)
                    // + textString);
                    mInfoList.get(INDEX_OTG).value = getString(R.string.usb_status_host)
                            + textString; // .put(TC_OTG,
                                            // getString(R.string.usb_status_host)
                                            // + textString);
                    mInfoList.get(INDEX_OTG).isAvaliable = true;
                    resultOtgOK = true;
                    mGridAdapter.notifyDataSetChanged();
                    is_pass = true;
                } else {
                    // mTextView_OTG.setText(getString(R.string.insert_otg_cable));
                    mInfoList.get(INDEX_OTG).value = getString(R.string.insert_otg_cable); // .put(TC_OTG,
                                                                                            // getString(R.string.insert_otg_cable));
                    mInfoList.get(INDEX_OTG).isAvaliable = false;
                    mGridAdapter.notifyDataSetChanged();
                }

            }
            // DoingMessage = false;

        }
    };

    private String callShellCmd_OTG(String cmd) {
        String textString = "";
        try {
            Process p = Runtime.getRuntime().exec(
                    new String[] { "sh", "-c", cmd });
            InputStream is = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String tmp = "";

            while ((tmp = br.readLine()) != null) {
                if (!tmp.contains("Host") && !tmp.contains("CDC-ACM")) {
                    textString += tmp;
                }

            }
            br.close();

            /*
             * InputStream eis =
             * p.getErrorStream();packages/apps/MAT/java/src/com
             * /intel/factorytest/activity/OTGTest.java:167: InputStreamReader
             * eisr = new InputStreamReader(eis); BufferedReader ebr = new
             * BufferedReader(eisr);
             * 
             * while((tmp=ebr.readLine())!=null){ textString += tmp; }
             * ebr.close();
             */
            p.destroy();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return textString;
    }

    @Override
    public void finish() {
        if (doBatteryStatusCheckTest) {
            updateTempTestcase(TC_BatteryStatusCheck, resultBatteryOK);
            // if (isSystemTest) {
            // try {
            // LogWriter.write(logFileName, tc);
            // } catch (IOException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            // }
        }
        if (doSdCardReadTest) {
            updateTempTestcase(TC_SdCard, resultSDCardOK);
            // if (isSystemTest) {
            // try {
            // LogWriter.write(logFileName, tc);
            // } catch (IOException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            // }
        }
        if (doUSBTest) {
            updateTempTestcase(TC_USB, resultUsbOK);
            // if (isSystemTest) {
            // try {
            // LogWriter.write(logFileName, tc);
            // } catch (IOException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            // }
        }
        if (doOTGTest) {
            updateTempTestcase(TC_OTG, resultOtgOK);
            // if (isSystemTest) {
            // try {
            // LogWriter.write(logFileName, tc);
            // } catch (IOException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            // }
        }


        // 记录综合测试大项log
        // boolean comprehensiveResult = isAllTestOK();
        updateTempTestcase(TEST_CASE_NAME, is_pass);
        // if (isSystemTest) {
        // try {
        // LogWriter.write(logFileName, tc);
        // } catch (IOException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        // }
        isLogged = true;
        // setTestResult();
        // tc.setTestResult(is_pass);
        // tc.setResultInfo(testcaseResultsInfo());
        super.finish();
    }

    private void updateTempTestcase(/* int index, */String name/*
                                                                 * , String
                                                                 * resInfo
                                                                 */,
            boolean result) {
        SharedPreferences pre = getSharedPreferences(
                MATApplication.LANGUAGE_PREF, Context.MODE_PRIVATE);
        String lanPre = pre.getString(MATApplication.LANGUAGE_KEY, "zh");
        if (lanPre.equals("zh"))
            name = nameMapping_language.get(name);
        System.out.println("tangjun Compre tc name=" + name);
        // tc.setTestCaseIndex(index);
        tc.setTestCaseName(name);
        // tc.setResultInfo(resInfo);
        tc.setTestResult(result);
    }

    private boolean isAllTestOK() {
        boolean batteryTestOK = false;
        boolean storageCardOK = false;
        boolean usbOK = false;
        boolean otgOK = false;
        boolean RFCalibOK = false;

        if (doBatteryStatusCheckTest) {
            if (resultBatteryOK) {
                batteryTestOK = true;
            }
        } else {
            batteryTestOK = true;
        }

        if (doSdCardReadTest) {
            if (resultSDCardOK) {
                storageCardOK = true;
            }
        } else {
            storageCardOK = true;
        }

        if (doUSBTest) {
            if (resultUsbOK) {
                usbOK = true;
            }
        } else {
            usbOK = true;
        }

        if (doOTGTest) {
            if (resultOtgOK) {
                otgOK = true;
            }
        } else {
            otgOK = true;
        }

        return batteryTestOK && storageCardOK && usbOK && otgOK;
    }

    private String testcaseResultsInfo() {
        StringBuilder sb = new StringBuilder();
        Iterator<SensorsTestActivity.ItemInfo> it = mInfoList.iterator();
        while (it.hasNext()) {
            SensorsTestActivity.ItemInfo itemInfo = it.next();
            sb.append("\n").append(itemInfo.name)
                    .append(itemInfo.isAvaliable ? " 成功 " : "失败 ")
                    .append("测试结果：").append(itemInfo.value).append("\n");
        }
        return sb.toString();
    }

    private String getTotalMemory() {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;

        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(
                    localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小

            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }

            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
            localBufferedReader.close();

        } catch (IOException e) {
        }
        return Formatter.formatFileSize(getBaseContext(), initial_memory);// Byte转换为KB或者MB，内存大小规格化
    }

    private String getTotalNand() {
        long size = 0;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(
                    "/sys/class/block/mmcblk0/size"));
            String sizeStr = "";
            if (null != (sizeStr = br.readLine())) {
                size = Integer.parseInt(sizeStr);
                // size = size / 2 / 1024 / 1024;
                size = size * 512;
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NumberFormatException e) {
            // TODO: handle exception
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        return Formatter.formatFileSize(getBaseContext(), size);
    }

    private long getTotalSize(String path) {
        synchronized (this) {
            Log.d(TAG, "path:" + path);
            try {
                StatFs statFs = null;
                File file = new File(path);
                if(false) {//user version fail!!!
                    File sdDir = new File("/dev/block/mmcblk1");
                    if (!sdDir.exists()) {
                      Log.d(TAG, "sdcard not insert");
                      return 0;
                    }
                } else {
                    boolean ismounted = Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED);
                    Log.e(TAG, "getTotalSize >>>> ismounted:" + ismounted);
                    if(!isSdcardMounted())
                        return 0;
                }
                if (file.exists()) {
                    statFs = new StatFs(path);

                    long blockSize = statFs.getBlockSize();
                    long totalBlocks = statFs.getBlockCount();
                    Log.d(TAG, "blockSize="+blockSize+",totalBlocks="+totalBlocks);
                    return blockSize * totalBlocks;
                } else {
                    Log.d(TAG, "file.exists()");
                    return 0;
                }
            } catch (Exception e) {
                Log.e(TAG, "Exception" + e.getMessage());
                return 0;
            }
        }

    }

    //get SD states,CHY
    private boolean isSdcardMounted(){
        boolean mounted = false;
        String line = null;
        BufferedReader reader = null;
        try{
            reader = new BufferedReader(new FileReader("/proc/mounts"));
            if(reader == null){
                Log.e(TAG, "isSdcardMounted >>> reader is NULL!!!");
                return mounted;
            }
            while ((line = reader.readLine()) != null) {
                String[] tmp = line.split(" ");
                if(tmp.length >= 2){
                    if(tmp[1] != null&& tmp[1].equals("/storage/sdcard1")){
                        mounted = true;
                        break;
                    }
                    Log.e(TAG, "isSdcardMounted >>> tmp:" + tmp[1]);
                }
            }
        }catch(FileNotFoundException e){
        }catch(IOException ee){
        }finally{
            try{
                if(reader != null)
                    reader.close();
            }catch(IOException eee){
            }
        }
        Log.d(TAG,"isSdcardMounted mounted:"+mounted);
        return mounted;
    }    
    
    private void TestExternStorage(boolean bSDCard, boolean bSetBGRed) {

        mTextString_Sdcard = getString(R.string.SERVICEMENU_RAM_TOTALSIZE_TXT)
                + sTotalMemorySize + "\n";
        mTextString_Sdcard += getString(R.string.SERVICEMENU_ROM_TOTALSIZE_TXT)
                + sTotalNandFlashSize + "\n";

        if (bSDCard) {
            mTextString_Sdcard += getString(R.string.SERVICEMENU_SDCARD_TOTALSIZE_TXT)
                    + sTotalSDCardhSize;

            mInfoList.get(INDEX_SdCard).isAvaliable = true;
            resultSDCardOK = true;
            mInfoList.get(INDEX_SdCard).isRedBg = false;
        } else {
            if (bSetBGRed) {
                mInfoList.get(INDEX_SdCard).isRedBg = true;
                mInfoList.get(INDEX_SdCard).isAvaliable = false;
                resultSDCardOK = false;
            }
            mTextString_Sdcard += getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT);
        }

        mInfoList.get(INDEX_SdCard).value = mTextString_Sdcard;

        mGridAdapter.notifyDataSetChanged();

    }

    private boolean ExistSDCard() {
        boolean bIsSDCardExist = false;
        String[] storagePathList = mStorageManager.getVolumePaths();
        if (storagePathList != null) {
            for (String path : storagePathList) {
                if (path.contains("sdcard1")) {
                    long size = getTotalSize(path);
                    sTotalSDCardhSize = Formatter.formatFileSize(
                            getBaseContext(), size);
                    if (size != 0) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

}
